<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="handleReset">
      <x-filter-item :label="'采购申请单号'">
        <el-input v-model="searchParams.number" :placeholder="'请输入'" maxlength="100" clearable></el-input>
      </x-filter-item>
      <x-filter-item :label="'部门'">
        <x-select-tree
          v-model="searchParams.deptId"
          ref="selectTree"
          :options="treeData"
          placeholder="请选择"
          :defaultProps="treeProps"
        />
      </x-filter-item>
      <x-filter-item :label="'采购申请类型'">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.type"
          :options="dictOptions['srm_purchase.type']"
          style="width: 100%"
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="'状态'">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['srm_purchase_detail.state']"
          style="width: 100%"
        ></x-select>
      </x-filter-item>
      <!-- <x-filter-item :label="'物料名称'">

      </x-filter-item> -->
      <x-filter-item :label="'日期'">
        <el-date-picker
          v-model="searchParams.createTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          :range-separator="$t('common.to')"
          :start-placeholder="'开始时间'"
          :end-placeholder="'结束时间'"
        >
        </el-date-picker>
      </x-filter-item>
    </x-filter>
    <x-data>
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button
              type="primary"
              @click="handleTransfer('purchaseOrder')"
              v-hasPermi="['purchase:demand:purchaseOrder']"
            >
            <i :class="['iconfont','el-icon--left','icon-zhuancaigoudingdan']"></i>{{ '转采购订单' }}</el-button
            >
            <el-button type="primary"  @click="handleTransfer('inquirySheet')" v-hasPermi="['purchase:demand:enquiry']">
              <i :class="['iconfont','el-icon--left','icon-zhuanxunjia']"></i>{{ '转询价' }}</el-button
            >
            <el-button type="danger" @click="handleCancel" v-hasPermi="['purchase:demand:cancel']">
              <i :class="['iconfont','el-icon--left','icon-tuihui']"></i>{{ '批量退回' }}</el-button
            >
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <span v-if="item.prop === 'type'">{{
              selectDictLabel(dictOptions['srm_purchase.type'], scope.row[item.prop])
            }}</span>
            <!-- <x-state-cell
              v-else-if="item.prop === 'state'"
              :text="selectDictLabel(dictOptions['srm_purchase_detail.state'], scope.row[item.prop])"
            /> -->
            <span v-else-if="item.prop === 'state'">{{
              selectDictLabel(dictOptions['srm_purchase_detail.state'], scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'materialUnit'">{{
              selectDictLabel(dictOptions['srm_material.material_unit'], scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'arrivalDate'">{{
               replaceDateTime(scope.row[item.prop]) 
            }}</span>
            
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :align="'center'" width="160">
          <template #default="scope">
            <more-table-actions
              :permis-list="permissionsActions"
              :action-list="getActions(actions, scope.row)"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
  </x-page>
</template>

<script>
import {
  buttonIcons,
  PermissionsMixin,
  QueryDictMixin,
  TableListMixin,
  selectDictLabel,
  replaceDateTime
} from '@package/utils'
import { mapState } from 'pinia'
import { columns, actions } from '@/modules/purchaseSearchSource/config/purchaseDemand.js'
import { listUrl, apiPostPurchaseDemandCancel } from '@/modules/purchaseSearchSource/api/purchaseDemand.js'
import { apiDeptTree } from '@/modules/config/api/index.js'
import { EnumApiCode } from '../../../../../../globalEnum.js'
import { pinias } from '@/common/pinia'

const { login } = pinias
export default {
  name: 'ManagePricing',
  mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
  data() {
    return {
      columns,
      actions,
      listUrl,
      treeLoading: false,
      treeData: [],
      treeProps: {
        label: 'deptName',
        children: 'children'
      },
      searchParams: {
        number: '',
        deptId: '',
        state: '',
        type: '',
        createTime: ''
      },
      tableData: [],
      srmDictKeys: ['srm_purchase_detail.state', 'srm_purchase.type', 'srm_material.material_unit']
    }
  },
  watch: {
    dictOptions: {
      handler(val) {
        console.log('val123', val)
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapState(login, ['user']),
    getActions() {
      return (actions) => {
        return actions.map((action) => {
          return action
        })
      }
    }
  },
  mounted() {
    this.loadTreeData()
  },
  methods: {
    buttonIcons,
    selectDictLabel,
    replaceDateTime,
    async loadTreeData() {
      this.treeLoading = true
      const { orgId } = this.user.mainPost
      const { data, code, msg } = await apiDeptTree({ orgId })
      this.treeLoading = false
      if (code === EnumApiCode.Success) {
        this.treeData = data
      } else {
        this.$message.error(msg)
      }
    },
    handleReset() {
      this.searchParams = {
        number: '',
        deptId: '',
        state: '',
        type: '',
        createTime: ''
      }
      this.resetSearch()
    },
    handleSearch(val) {
      const { number, state, deptId, type, createTime } = this.searchParams
      this.queryParam = {
        ...val,
        number,
        state,
        deptId,
        type,
        beginTime: createTime ? `${createTime[0]} 00:00:00` : '',
        endTime: createTime ? `${createTime[1]} 23:59:59` : ''
      }
      this.loadData()
    },
    async handleActions({ key, data }) {
      const { id } = data
      switch (key) {
        case 'detail':
          this.$router.push({
            name: 'PurchanseDemandDetail',
            query: {
              id
            }
          })
          break
        default:
          break
      }
    },
    // 取消
    handleCancel() {
      if (this.selectionRows.length === 0) {
        this.$message.error('请至少选择一条数据操作')
        return
      }
      this.$confirm('确认取消操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((confirm) => {
          this.cancel(this.selectedRowKeys)
        })
        .catch((cancel) => {})
    },
    async cancel(ids) {
      const { code, msg } = await apiPostPurchaseDemandCancel(ids)
      if (code === EnumApiCode.Success) {
        this.$message.success('发送成功')
        this.loadData()
      } else {
        this.$message.error(msg)
      }
    },
    // 转采购订单或者询价单
    handleTransfer(flowCode) {
      if (this.selectionRows.length === 0) {
        this.$message.error('请至少选择一条数据操作')
        return
      }
      if (
        this.selectionRows.some((row) => {
          return row.state !== 0
        })
      ) {
        this.$message.error('请选择待处理状态数据操作')
        return
      }
      this.$router.push({
        name: 'flowLaunch',
        query: {
          params: JSON.stringify(this.selectionRows),
          flowCode
        }
      })
    }
  }
}
</script>

<style scoped></style>
